package com.example.sunny.service.receiver

import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.util.Log
import androidx.core.app.NotificationCompat
import com.example.sunny.SunnyApplication
import com.example.sunny.pojo.location.MyLocation
import com.example.sunny.pojo.weather.Weather
import com.example.sunny.pojo.weather.getSky
import com.example.sunny.service.Repository
import com.example.sunny.service.network.location.LocationService
import com.example.sunny.view.weather.WeatherActivity


class AlarmReceiver:BroadcastReceiver(),LocationService.MyLocationListener.LocationCallback{

    var myLocation:MyLocation? = null
    lateinit var weather: Weather
    override fun onReceive(context: Context?, intent: Intent?) {
        Log.d("OnReceive","进入receive")            //获得定位
        val locationClient = LocationService.initLocation(SunnyApplication.context, this)
        locationClient.start()
        locationClient.requestLocation()

        val manager = context?.getSystemService(Context.NOTIFICATION_SERVICE)  as NotificationManager
        val channel = NotificationChannel("weather","天气",NotificationManager.IMPORTANCE_DEFAULT)
        manager.createNotificationChannel(channel)
        manager.createNotificationChannel(channel)

        while (myLocation==null){
            locationClient.requestLocation()
        }
        myLocation?.apply {
            val refreshWeather =
                Repository.refreshWeather(lng.toString(), lat.toString(), context)
            weather = refreshWeather.value?.getOrNull()!!
        }

        val temperature = weather.daily.temperature[0].run {
            "${min.toInt()}~${max.toInt()} ℃"
        }
        val skycon = getSky(weather.daily.skycon[0].value).info
        val intent = Intent(context,WeatherActivity::class.java)
        val pendingIntent = PendingIntent.getActivity(context,0,intent,0)

        val notification = NotificationCompat.Builder(context,"weather")
            .setContentTitle("Sunny 向您推送今天的天气~")
            .setContentText("${myLocation?.city} 天气:${skycon} 温度:${temperature}")
            .setContentIntent(pendingIntent)
            .setAutoCancel(true)
            .build()

        manager.notify(1,notification)

        if (intent?.action==AlarmTimer.TIMER_ACTION_REPEATING){
        }
    }

    override fun getLocation(myLocation: MyLocation) {
        this.myLocation = myLocation
    }

}